#include "demuxthread.h"
#include <QDebug>


namespace wxb{
DemuxThread::DemuxThread(QObject *parent)
    : QThread{parent}
{
}

void DemuxThread::run(){
    while (!exitFlag) {
        //读取一个packet
        AVPacket* pkt = demuxMedia.readPacket();
        if (!pkt) {
            msleep(5);
            continue;
        }
        //判断数据是音频
        if (pkt->stream_index == demuxMedia.getAudioIndex()) {
            //放入缓冲队列中
            if(audioThread) {
                audioThread->addPktToCache(pkt);
            }
        }
        else if(pkt->stream_index == demuxMedia.getVideoIndex()) {
            if (videoThread) {
                videoThread->addPktToCache(pkt);
            }
        }
    }
}

void DemuxThread::startAll()
{
    QThread::start();
    videoThread->start();
    audioThread->start();
}

bool DemuxThread::open(const char *url)
{
    bool ret = demuxMedia.openMediaStream(url);
    if(ret){
        videoThread = new VideoThread();
        audioThread = new AudioThread();
        AVCodecParameters* videoParams = demuxMedia.copyAVCodecParams(demuxMedia.getVideoIndex());
        ret = videoThread->openDecoder(videoParams);
        if(!ret){
            qDebug() << "DemuxThread::startAll() videoThread->openDecoder(videoParams); error";
            avcodec_parameters_free(&videoParams);
            return ret;
        }
        AVCodecParameters* audioParams = demuxMedia.copyAVCodecParams(demuxMedia.getAudioIndex());
        ret = audioThread->openDecoder(audioParams);
        if(!ret){
            qDebug() << "DemuxThread::startAll() audioThread->openDecoder(audioParams); error";
            avcodec_parameters_free(&audioParams);
            return ret;
        }
    }
    return ret;
}
}
